// pages/installationEvaluationDetail/installationEvaluationDetail.js
import WxValidate from "../../utils/WxValidate"
import { queryQuestionByType, queryEvaluateInfo, saveEvaluate } from '../../api/evaluate'
let app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    state: 'save',
    questionLists: [],
    formData: {
      evaluateLevel: 0,
      remark: ''
    },
    WxValidate: undefined
  },
  //   查询评价试题
  queryQuestionByType() {
    wx.showLoading({
      title: '加载中',
    })
    queryQuestionByType({type: '0'}).then(res => {
        let { data, success } = res
        if (success) {
            this.setData({
                questionLists: data
            })
        }
        this.initValidate()//验证规则函数
      wx.hideLoading()
    })
  },
  queryEvaluateInfo() {
    wx.showLoading({
      title: '加载中',
    })
    queryEvaluateInfo({id: this.data.formData.id}).then(res => {
        let { data, success } = res
        if (success) {
            this.setData({
                formData: data,
                questionLists: data.answerJson
            })
        }
        this.initValidate()//验证规则函数
      wx.hideLoading()
    })
  },
  onRateChange(event) {
    this.setData({
      'formData.evaluateLevel': event.detail,
    });
  },

  afterRead(event) {
      let _this = this
      wx.showLoading({
          title: '加载中',
      })
      const {file} = event.detail;
      wx.uploadFile({
          url: `${app.globalData.baseUrl}/sys/attachment/upload`,
          filePath: file.url,
          name: 'file',
          success(res) {
              let {data, success} = JSON.parse(res.data)
              if (success) {
                  _this.setData({
                      'formData.logisticsImg': data.attachment
                  })
              }
              wx.hideLoading()
          }
      });
  },
  deleteImg(e) {
      this.setData({
          'formData.logisticsImg': ''
      })
  },
  //报错 
  showModal(error) {
    wx.showToast({
      title: error.msg,
      icon: 'none',
      duration: 2000
    })
  },
  //验证函数
  initValidate() {
    const rules = {}
    const messages = {}
    this.data.questionLists.forEach((item, index) => {
        const key = item['title']
        if (key) {
            rules[key] = {
                            required: true
                        }
            messages[key] = {
                                required: `请选择第${index + 1}个问题`
                            }
        }
    })
    
    this.WxValidate = new WxValidate(rules, messages)
  },
  //调用验证函数
  formSubmit: function(e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    if (this.data.formData.evaluateLevel === 0) {
        this.showModal({msg: '请选择总体评价'})
        return
    }
    this.data.questionLists.forEach(item => {
        item.result = params[item.title]
    })
    this.setData({
        'formData.remark': params.remark,
        'formData.answerList': this.data.questionLists
    })
    wx.showLoading({
      title: '提交中',
    })
    saveEvaluate(this.data.formData).then(res => {
        let { message, success } = res
        if (success) { 
            wx.showToast({
                title: message,
                duration: 2000,
                success: () => {
                    setTimeout(() => {
                        wx.navigateTo({
                            url: '/pages/home/home'
                        })
                    }, 2000);
                }
            })
        }
        wx.hideLoading()
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
        this.setData({
            state: options.state,
            'formData.id': options.id,
            'formData.userId': app.globalData.userId
        })
        if (options.state === 'save') {
            this.queryQuestionByType()
        } else {
            this.queryEvaluateInfo()
        }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})